package com.data.action;

import com.data.bean.Account;
import com.data.entity.User;
import com.data.listener.SessionLoginListener;
import com.data.service.LoginService;
import com.data.util.ForceLogoutUtils;
import com.data.util.VerificationCodeUtil;
import com.mysql.jdbc.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

@Controller
@RequestMapping("/android/loginAction")
public class LoginAction {
    @Autowired
    private LoginService loginService;

    /**
     * 进入到登陆界面,如果cookie中有账号与密码，就填写到文本框中，即记住密码操作
     *
     * @return
     */
    @RequestMapping(value = "/login/input", method = RequestMethod.GET)
    public String loginInputAction(Model model, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie c : cookies) {
                if (c.getName().equals("username")) {
                    model.addAttribute("username", c.getValue());
                } else if (c.getName().equals("password")) {
                    model.addAttribute("password", c.getValue());
                }
            }
        }

        return "login";
    }

    /**
     * 请求验证码
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/login/authcode", method = RequestMethod.GET)
    public void getAuthCodeAction(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取验证码
        String authcode = VerificationCodeUtil.getAuthCode();
        //添加验证码到session中
        request.getSession().setAttribute("authcode", authcode);
        BufferedImage authImage = VerificationCodeUtil.getAuthImage(authcode);
        byte[] inputStream = convertImageToStream(authImage);
        response.setContentType("image/png");
        OutputStream stream = response.getOutputStream();
        stream.write(inputStream);
        stream.flush();
        stream.close();
    }


    /**
     * 验证码校验,随机验证码，手机验证码都可以用这个来做校验
     *
     * @param ucode   传入的验证码
     * @param request
     * @return
     */
    @RequestMapping(value = "/login/authCodeCheck")
    @ResponseBody
    public String authCodeCheckAction(@RequestParam(value = "ucode") String ucode, HttpServletRequest request) {
        String authcode = (String) request.getSession().getAttribute("authcode");
        ucode = ucode.trim().toLowerCase();
        // 如果验证码是空，就赋值为空格
        authcode = authcode != null ? authcode.toLowerCase() : " ";
        boolean bool = authcode.equals(ucode);
        return String.valueOf(bool);
    }

    /**
     * 管理员，上传用户登录模块
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/login/submit", method = RequestMethod.POST)
    public String loinAction(User user, HttpServletRequest request) {
        System.out.println(user);
        if (user != null && !StringUtils.isNullOrEmpty(user.getUsername())) {
            Account account = loginService.loginMethodService(user);
            if (account != null) {
                HttpSession session = request.getSession();
                if (null != SessionLoginListener.sessionMap.get(account.getId())) {
                    /**
                     * 将已经登陆的信息拿掉,将新的用户登录信息放进去
                     */
                    System.out.println("将已经登陆的信息拿掉,将新的用户登录信息放进去");
                    ForceLogoutUtils.forceUserLogout(account.getId());
                    SessionLoginListener.sessionMap.put(account.getId(), session);
                } else {
                    /**
                     * 该账号未被登陆
                     */
                    System.out.println("该账号未被登陆");
                    SessionLoginListener.sessionMap.put(account.getId(), session);
                }

                //添加登录信息到session中
                request.getSession().setAttribute("Account", account);
                //账号激活
                if (account.isState()) {
                    return "redirect:/indexAction/admin/index";
                } else {
                    //重定向到注册完成界面，让发送邮件，继续激活该邮箱
                    request.getSession().setAttribute("Account", account);
                    return "redirect:/android/registAction/emailFish";
                }

            }
        }
        request.setAttribute("bool", "账号或者密码错误");
        return "login";
    }


    /**
     * 将图片转化为字节流
     *
     * @param image
     * @return
     */
    private byte[] convertImageToStream(BufferedImage image) {
        ByteArrayInputStream inputStream = null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            // 将图片流写入发哦输出流中
            ImageIO.write(image, "jpeg", out);
        } catch (IOException e) {

            e.printStackTrace();
        }
        // 讲图片流转化为字节数组流
        byte[] bts = out.toByteArray();
        return bts;
    }

    @RequestMapping("person/index")
    public String inputPerson() {
        return "/WEB-INF/person/index";
    }

    @RequestMapping("company/index")
    public String inputConpany() {
        return "/WEB-INF/company/index";
    }


    public LoginService getLoginService() {

        return loginService;
    }

    public void setLoginService(LoginService loginService) {
        this.loginService = loginService;
    }

}
